import { Text, View } from "@tarojs/components";
import { Dialog, Input } from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";
import { useState } from "react";
import { exchangeCode } from "@/api/my";
const Exchange = ({
  codeOpen,
  setCodeOpen,
  onExchange,
}: {
  codeOpen: boolean;
  setCodeOpen: (data: boolean) => void;
  onExchange: () => void;
}) => {
  const [code, setCode] = useState<string>("");
  return (
    <Dialog
      visible={codeOpen}
      onCancel={() => {
        setCodeOpen(false);
        setCode("");
      }}
      confirmText="兑换"
      cancelText="关闭"
      onConfirm={() => {
        if (code) {
          exchangeCode(code).then((res) => {
            if (res.data) {
              Taro.showToast({
                title: "激活成功",
                icon: "none",
              });
              setCodeOpen(false);
              setCode("");
              onExchange();
            }
          });
        } else {
          Taro.showToast({
            title: "请输入激活码",
            icon: "none",
          });
        }
      }}
    >
      <View className="relative">
        <Input
          style={{ "--nutui-input-border-bottom-width": "1px" }}
          value={code}
          onChange={(value) => setCode(value)}
          placeholder="请输入合集兑换码"
          maxLength={8}
          type="text"
          autoFocus
        />
        <Text className="text-xs text-black/50 absolute right-1 top-4">
          {code?.length + "/8"}
        </Text>
      </View>
    </Dialog>
  );
};

export default Exchange;
